package com.gable.exhibition.service.impl;

import com.alibaba.fastjson.JSON;
import com.gable.common.util.*;
import com.gable.exhibition.dao.*;
import com.gable.exhibition.init.ItemInIt;
import com.gable.exhibition.init.MaintainerManufacturerInit;
import com.gable.exhibition.init.ManufacturerInit;
import com.gable.exhibition.init.SupplierManufacturerInit;
import com.gable.exhibition.model.*;
import com.gable.exhibition.service.RepairService;
import com.gable.exhibition.service.UserService;
import com.gable.exhibition.thread.*;
import com.gable.exhibition.util.ExceptionUtil;
import com.gable.exhibition.util.HttpHelper;
import com.gable.exhibition.util.InsideOutsideUtil;
import com.gable.exhibition.util.MessageUtil;
import com.gable.exhibition.view.*;
import com.gable.exhibition.websocket.WSClientManager;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 乔春峰 on 2018/2/26.
 */
@Service("repairService")
public class RepairSerivceImpl implements RepairService{

    @Value("${repairByPlatform1}")
    String repairByPlatform1;       //医院报修平台短信URL

    @Value("${repairByService1}")
    String repairByService1;        //指派服务商短信URL

    @Value("${repairByEngineer}")
    String repairByEngineer;        //指派给工程师短信URL

    @Value("${repairByDoctor1}")
    String repairByDoctor1;   //工程师响应短信URL

    @Value("${repairByDoctor2}")
    String repairByDoctor2; //工程师处理短信URL

    @Value("${repairByService2}")
    String repairByService2;    //医院确认通过

    @Value("${repairByPlatform2}")
    String repairByPlatform2;   //医院确认未通过

    @Value("${webSocket_InsertRepairUrl}")
    String webSocket_InsertRepairUrl;       //维修流程创建群组

    @Value("${webSocket_endRepairUrl}")
    String webSocket_endRepairUrl;  //流程结束解散群组

    @Autowired
    RepairDao repairDao;

    @Autowired
    EventDao eventDao;

    @Autowired
    DeviceDao deviceDao;

    @Autowired
    UserDao userDao;

    @Autowired
    FileDao fileDao;

    @Autowired
    PartDao partDao;

    @Autowired
    UserService userService;

    @Autowired
    MaintainerDao maintainerDao;

    @Autowired
    ContractDeviceDao contractDeviceDao;

    @Autowired
    ContractDao contractDao;

    @Autowired
    SupplierDao supplierDao;

    @Autowired
    ManufacturerDao manufacturerDao;

    @Autowired
    AppointDao appointDao;

    @Autowired
    ValidateCodeDao validateCodeDao;

    @Autowired
    HospitalDao hospitalDao;
    /**
     * 添加报修
     * @param repair
     * @return
     */
    @Override
    @Transactional
    public ReturnResultUtil add(RepairView repair){
        // 添加报修
        DeviceView dc = deviceDao.queryDeviceInfo(repair.getDeviceId());
        repair.setRepairId(UUIDGenerator.getUniqueLong()); // ID
        repair.setRepairNo("WX"+UUIDGenerator.getUniqueLong());// 报修编号
        repair.setRepairTime(DateUtils.getCurrentTime());  //报修时间
        repair.setRepairDeviceStartStatus(repair.getDeviceStatus());
        repair.setHospitalId(dc.getHospitalId());          // 医院ID
        repair.setStatus(2200L);                           // 待处理
        repair.setCommentStatus(3502L);                    //未评论(已评论:3501,未评论:3502,已回复:3503)
        repair.setIsDel(0);                                // 禁用状态（1禁用，0正常）
        repair.setCreatePerson(repair.getUserId());          // 创建人
        repair.setCreateTime(DateUtils.getCurrentTime());  // 创建时间
        int result = repairDao.insertSelective(repair);
        // 添加成功
        if(result > 0){
            List<String> fileIds = repair.getFileIds();
            if(fileIds != null && fileIds.size()>0){
                for(String fileId : fileIds){
                    File file = new File();
                    file.setFileId(Long.parseLong(fileId));
                    file.setKeyId(repair.getRepairId());
                    result = fileDao.updateByPrimaryKeySelective(file);
                    if(result == 0)
                        throw new ExceptionUtil(500,MessageUtil.UPLOADEXCEPTION,file);
                }
            }

            // 修改设备状态
            Device device = new Device();
            device.setDeviceId(repair.getDeviceId());
            device.setDeviceStatus(repair.getDeviceStatus());
            result = deviceDao.updateByPrimaryKeySelective(device);
            if(result == 0)
                throw new ExceptionUtil(500,MessageUtil.UPDATEDEVICEERROR);
            // 创建事件对象
            Event event = new Event();
            // 添加报修事件
            event.setEventId(UUIDGenerator.getUniqueLong());
            event.setKeyType(1601L);
            event.setKeyId(repair.getRepairId());       // 维修ID
            event.setEventDateTime(DateUtils.getCurrentTime());
            //什么都没选择
            if(repair.getServiceType()==null){
                event.setEventContent(StringUtil.isEmpty(repair.getRepairPerson())==null?"":repair.getRepairPerson()+"于"+repair.getRepairTime()+"报修了("+dc.getDeviceName()+"),待平台处理");
            }else{
                if(repair.getIsDispatch()==1){
                    event.setEventContent(StringUtil.isEmpty(repair.getRepairPerson())==null?"":repair.getRepairPerson()+"于"+repair.getRepairTime()+
                            "报修了("+dc.getDeviceName()+")并安排"+getName(repair.getServiceType())+"("+ repair.getServiceName()+")指派了工程师("+repair.getEngineerName()+")维修,待平台处理");
                }else{
                    event.setEventContent(StringUtil.isEmpty(repair.getRepairPerson())==null?"":repair.getRepairPerson()+"于"+repair.getRepairTime()+
                            "报修了("+dc.getDeviceName()+")并安排"+getName(repair.getServiceType())+"("+ repair.getServiceName()+"),待平台处理");
                }
            }
            event.setEventTitle("申请报修");
            event.setCreatePerson(repair.getCreatePerson());
            event.setCreateTime(DateUtils.getCurrentTime());
            event.setIsDel(0);
            result = eventDao.insertSelective(event);
            if(result == 0)
                throw new ExceptionUtil(500,MessageUtil.INSERTEVENTERROR);
            // 添加设备事件
            event.setEventId(UUIDGenerator.getUniqueLong());
            event.setKeyType(1601L);
            event.setKeyId(repair.getDeviceId());       // 设备ID
            event.setEventDateTime(DateUtils.getCurrentTime());
            if(repair.getIsDispatch()==1){
                event.setEventContent("医院-"+repair.getHospitalName()+"向"+repair.getServiceName()+"申请报修,处理人为："+repair.getEngineerName());
            }else{
                event.setEventContent("设备申请报修");
            }
            event.setEventTitle("设备报修");
            event.setType(1700L);
            event.setCreatePerson(repair.getCreatePerson());
            event.setCreateTime(DateUtils.getCurrentTime());
            event.setIsDel(0);
            result = eventDao.insertSelective(event);
            if(result == 0)
                throw new ExceptionUtil(500,MessageUtil.INSERTEVENTERROR);

            Thread t = new Thread(new Runnable() { //socket 推送
                @Override
                public void run() {
                    try {
                        sendUkeepMessageBySocket(repair);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            t.start();

            //创建群组
            new Thread(new ChatGroupThread(repair.getRepairId()+"",webSocket_InsertRepairUrl)).start();

            //推送短信给平台管理员
            String hospitalName = dc.getHospitalName();
            String deviceName = dc.getDeviceName();
            String sn = dc.getSn();

            new Thread(new RepairSendSmsThread(hospitalName,deviceName,sn,userDao,repairByPlatform1,null)).start();

            return new ReturnResultUtil(200, MessageUtil.SAVESUCCESS,repair);
        }
        return new ReturnResultUtil(200, MessageUtil.SAVEEXCEPTION);
    }

    /**
     * 获取维修list集合
     * @param repairView
     * @return
     */
    @Override
    public ReturnResultUtil list(RepairView repairView) {
        int count = repairDao.count(repairView);
        List<RepairView> list = repairDao.list(repairView);
        RepairView rv = new RepairView();
        rv.setCount(count);
        rv.setList(list);
        return new ReturnResultUtil(200, MessageUtil.QUERYSUCCESS,rv);
    }

    /**
     * 平台分配
     * @param repairView
     * @return
     */
    @Override
    @Transactional
    public ReturnResultUtil distribution(RepairView repairView,UserView sessionUser){
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        repairView.setStatus(2201L);

        AppointView av = new AppointView();
        av.setKeyId(repairView.getRepairId());

        //更新上一条指派响应时间
        Appoint app = appointDao.queryLastAppoint(av);
        if(app!=null){
            app.setResponseTime(df.format(new Date()));
            int result = appointDao.updateByPrimaryKey(app);
            if(result == 0)
                throw new ExceptionUtil(500,MessageUtil.APPOINTERROR);
        }

        Appoint appoint = this.setAppoint(repairView,sessionUser);
        if(appoint==null)
            throw new ExceptionUtil(500,MessageUtil.FAILED);

        if(sessionUser.getType()==1104L){
            repairView.setHandleTime(df.format(new Date()));
            repairView.setFrontStatus(2200L);
        }else{
            repairView.setFrontStatus(2201L);
        }
        int result = repairDao.updateByDistribution(repairView);
        if(result == 0)
            throw new ExceptionUtil(500,MessageUtil.DISTRIBUTIONERROR);

        result = appointDao.insertSelective(appoint);
        if(result == 0)
            throw new ExceptionUtil(500,MessageUtil.DISTRIBUTIONERROR);

        Repair repair = repairDao.selectByPrimaryKey(repairView.getRepairId());
        // 添加事件
        Event event = new Event();
        event.setEventId(UUIDGenerator.getUniqueLong());
        event.setKeyType(1601L);
        event.setKeyId(repairView.getRepairId());
        event.setEventDateTime(df.format(new Date()));
        event.setEventTitle("分配服务商");
        if(repair.getDeviceId()!=null){
            DeviceView dc = deviceDao.queryDeviceInfo(repair.getDeviceId());
            if(sessionUser.getType()==1104L){
                if(repairView.getStatus()== 2206L){
                    event.setEventContent(StringUtil.isEmpty(repair.getRepairPerson())==null?"":repair.getRepairPerson()+"于"+repair.getRepairTime()+
                            "报修的("+dc.getDeviceName()+"),平台安排"+getName(repair.getServiceType())+"("+ repair.getServiceName()+")并指派了工程师("+repair.getEngineerName()+"),电话:"+repair.getEngineerPhone()+",待工程师处理");
                }else{
                    event.setEventContent(StringUtil.isEmpty(repair.getRepairPerson())==null?"":repair.getRepairPerson()+"于"+repair.getRepairTime()+
                            "报修的("+dc.getDeviceName()+"),平台安排"+getName(repair.getServiceType())+"("+ repair.getServiceName()+"),待("+repair.getServiceName()+")处理");
                }
            }else{
                if(repairView.getStatus()== 2206L){
                    event.setEventContent(StringUtil.isEmpty(repair.getRepairPerson())==null?"":repair.getRepairPerson()+"于"+repair.getRepairTime()+
                            "报修的("+dc.getDeviceName()+"),"+sessionUser.getRealName()+"安排"+getName(repair.getServiceType())+"("+ repair.getServiceName()+")并指派了工程师("+repair.getEngineerName()+"),电话:"+repair.getEngineerPhone()+",待工程师处理");
                }else{
                    event.setEventContent(StringUtil.isEmpty(repair.getRepairPerson())==null?"":repair.getRepairPerson()+"于"+repair.getRepairTime()+
                            "报修的("+dc.getDeviceName()+"),"+sessionUser.getRealName()+"安排"+getName(repair.getServiceType())+"("+ repair.getServiceName()+")处理");
                }
            }
        }else{
            if(sessionUser.getType()==1104L){
                if(repairView.getStatus()== 2206L){
                    event.setEventContent(StringUtil.isEmpty(repair.getRepairPerson())==null?"":repair.getRepairPerson()+"于"+repair.getRepairTime()+
                            "报修了设备,平台安排"+getName(repair.getServiceType())+"("+ repair.getServiceName()+")并指派了工程师("+repair.getEngineerName()+"),电话:"+repair.getEngineerPhone()+",待工程师处理");
                }else{
                    event.setEventContent(StringUtil.isEmpty(repair.getRepairPerson())==null?"":repair.getRepairPerson()+"于"+repair.getRepairTime()+
                            "报修了设备,平台安排"+getName(repair.getServiceType())+"("+ repair.getServiceName()+"),待("+repair.getServiceName()+")处理");
                }
            }else{
                if(repairView.getStatus()== 2206L){
                    event.setEventContent(StringUtil.isEmpty(repair.getRepairPerson())==null?"":repair.getRepairPerson()+"于"+repair.getRepairTime()+
                            "报修了设备,"+sessionUser.getRealName()+"安排"+getName(repair.getServiceType())+"("+ repair.getServiceName()+")并指派了工程师("+repair.getEngineerName()+"),电话:"+repair.getEngineerPhone()+",待工程师处理");
                }else{
                    event.setEventContent(StringUtil.isEmpty(repair.getRepairPerson())==null?"":repair.getRepairPerson()+"于"+repair.getRepairTime()+
                            "报修了设备,"+sessionUser.getRealName()+"安排"+getName(repair.getServiceType())+"("+ repair.getServiceName()+")处理");
                }
            }
        }
        event.setCreatePerson(repairView.getUserId());
        event.setCreateTime(df.format(new Date()));
        event.setIsDel(0);
        result = eventDao.insertSelective(event);
        if(result == 0)
            throw new ExceptionUtil(500,MessageUtil.INSERTEVENTERROR);


        Thread t = new Thread(new Runnable() { //socket 推送
            @Override
            public void run() {
                try {
                    sendUkeepMessageBySocket(repairView);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        t.start();

        //创建群组
        new Thread(new ChatGroupThread(repairView.getRepairId()+"",webSocket_InsertRepairUrl)).start();
        //发送短信
        new Thread(new DispatchSendSmsThread(repairView.getRepairId(),1,userDao,repairDao,null,
                repairByService1,repairByEngineer,null,null)).start();

        return new ReturnResultUtil(200,MessageUtil.SUCCESSFUL);
    }

//    /**
//     * 指派工程师
//     * @param repairView
//     * @return
//     */
//    @Override
//    @Transactional
//    public ReturnResultUtil assignEngineer(RepairView repairView){
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        ReturnResultUtil rru = userService.queryUserByEngineerPhone(repairView.getEngineerPhone(),repairView.getEngineerName(),repairView.getServiceId(),repairView.getServiceType());
//        if(rru.getData() == null)
//            return new ReturnResultUtil(rru.getRet(),rru.getMsg());
//        User user1 = (User) rru.getData();
//        repairView.setEngineerId(user1.getUserId());
//        repairView.setStatus(2202L);                                // 待维修
//        int result = repairDao.update(repairView);
//        if(result == 0)
//            throw new ExceptionUtil(500,MessageUtil.UPDATEREPAIRERROR,repairView);
//        // 添加事件
//        Event event = new Event();
//        event.setEventId(UUIDGenerator.getUniqueLong());
//        event.setKeyType(1601L);
//        event.setKeyId(repairView.getRepairId());       // 设备ID
//        event.setEventDateTime(DateUtils.getCurrentTime());
//        event.setEventContent("指派工程师");
//        event.setEventTitle("指派工程师");
//        event.setCreatePerson(repairView.getUserId());
//        event.setCreateTime(DateUtils.getCurrentTime());
//        event.setIsDel(0);
//        result = eventDao.insertSelective(event);
//        if(result == 0)
//            throw new ExceptionUtil(500,MessageUtil.INSERTEVENTERROR,event);
//        //平台分配后推送短信
//        SmsView smsView = repairDao.repairForSms(repairView.getRepairId());
//        String hospitalName = smsView.getHospitalName();
//        String serverName = smsView.getServerName();
//        String deviceName = smsView.getDeviceName();
//        String engineerName = smsView.getEngineerName();
//        String engineerMobile = smsView.getEngineerMobile();
//        String createPersonMobile = smsView.getCreatePersonMobile();
//        List<String> serverMobile = smsView.getServerMobile();
//
//        Thread t = new Thread(new Runnable() { //socket 推送
//            @Override
//            public void run() {
//                try {
//                    sendUkeepMessageBySocket(repairView);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//        });
//        t.start();
//
//        //创建群组
//        new Thread(new ChatGroupThread(repairView.getRepairId()+"",webSocket_InsertRepairUrl)).start();
//
////        new Thread(new DispatchSendSmsThread(hospitalName,serverName,deviceName,engineerName,
////                engineerMobile,createPersonMobile,serverMobile,
////                sendSmsServerForRepairUrl,sendSmsHospitalForAssignEngineerUrl,
////                sendSmsEngineerForAssignEngineerUrl)).start();
//        return new ReturnResultUtil(200,MessageUtil.SUCCESSFUL);
//    }

    /**
     * 工程师响应操作
     * @param repairView
     * @return
     */
    @Override
    public ReturnResultUtil engineerResponse(RepairView repairView) {
        repairView.setFrontStatus(2206L);
        repairView.setEngineerResponseTime(DateUtils.getCurrentTime());
        repairView.setStatus(2202L);     // 待确认
        int result = repairDao.updateByDistribution(repairView);
        if(result == 0)
            throw new ExceptionUtil(500,MessageUtil.UPDATEREPAIRERROR);
        // 添加事件
        Event event = new Event();
        event.setEventId(UUIDGenerator.getUniqueLong());
        event.setKeyType(1601L);
        event.setKeyId(repairView.getRepairId());       // 设备ID
        event.setEventDateTime(DateUtils.getCurrentTime());
        event.setEventContent("工程师预计"+repairView.getEngineerExpectedTime()+"到医院维修");
        event.setEventTitle("工程师已响应");
        event.setCreatePerson(repairView.getUserId());
        event.setCreateTime(DateUtils.getCurrentTime());
        event.setIsDel(0);
        result = eventDao.insertSelective(event);
        if(result == 0)
            throw new ExceptionUtil(500,MessageUtil.INSERTEVENTERROR,event);


        Thread t = new Thread(new Runnable() { //socket 推送
            @Override
            public void run() {
                try {
                    sendUkeepMessageBySocket(repairView);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        t.start();
        new Thread(new EngineerResponseSmsThread(repairView.getRepairId(),1,repairDao,
                null,repairByDoctor1,null)).start();
        return new ReturnResultUtil(200,MessageUtil.SUCCESSFUL);
    }

    /**
     * 工程师开始维修
     * @param repair
     * @return
     */
    @Override
    @Transactional
    public ReturnResultUtil startRepair(RepairView repair){
        repair.setFrontStatus(2202L);
        repair.setStatus(2203L);                                // 待确认
        int result = repairDao.updateByDistribution(repair);
        if(result == 0)
            throw new ExceptionUtil(500,MessageUtil.UPDATEREPAIRERROR);
        List<String> fileIds = repair.getFileIds();
        if(fileIds != null && fileIds.size() > 0){
            for(String fileId : fileIds){
                File file = new File();
                file.setFileId(Long.parseLong(fileId));
                file.setKeyId(repair.getRepairId());
                result = fileDao.updateByPrimaryKeySelective(file);
                if(result == 0)
                    throw new ExceptionUtil(500,MessageUtil.UPLOADEXCEPTION,file);
            }
        }
        // 修改设备状态
        Device device = new Device();
        device.setDeviceId(repair.getDeviceId());
        device.setDeviceStatus(repair.getRepairDeviceEndStatus());      // 维修结束设备状态
        deviceDao.updateByPrimaryKeySelective(device);
        if(result == 0)
            throw new ExceptionUtil(500,MessageUtil.UPDATEDEVICEERROR);

        // 添加事件
        Event event = new Event();
        event.setEventId(UUIDGenerator.getUniqueLong());
        event.setKeyType(1601L);
        event.setKeyId(repair.getRepairId());       // 设备ID
        event.setEventDateTime(DateUtils.getCurrentTime());
        event.setEventContent("工程师已维修完成，待医院审核");
        event.setEventTitle("工程维修完成");
        event.setCreatePerson(repair.getUserId());
        event.setCreateTime(DateUtils.getCurrentTime());
        event.setIsDel(0);
        result = eventDao.insertSelective(event);
        if(result == 0)
            throw new ExceptionUtil(500,MessageUtil.INSERTEVENTERROR,event);


        Thread t = new Thread(new Runnable() { //socket 推送
            @Override
            public void run() {
                try {
                    sendUkeepMessageBySocket(repair);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        t.start();

        new Thread(new EngineerDoSmsThread(repair.getRepairId(),1,repairDao,
                null,repairByDoctor2,null)).start();

        return new ReturnResultUtil(200,MessageUtil.SUCCESSFUL);
    }

    /**
     * 维修确认
     * @param repair
     * @return
     */
    @Override
    @Transactional
    public ReturnResultUtil confirm(RepairView repair){
        if(repair.getStatus()==2205L){
            return this.reject(repair);
        }else{
            repair.setFrontStatus(2203L);
            repair.setCommentStatus(3501L);                    //已评论(已评论:3501,未评论:3502,已回复:3503)
            int result = repairDao.updateByDistribution(repair);
            if(result == 0)
                throw new ExceptionUtil(500,MessageUtil.UPDATEREPAIRERROR,repair);
            // 添加事件
            Event event = new Event();
            event.setEventId(UUIDGenerator.getUniqueLong());
            event.setKeyType(1601L);
            event.setKeyId(repair.getRepairId());       // 设备ID
            event.setEventDateTime(DateUtils.getCurrentTime());
            event.setEventContent("医院审核通过并评分");
            event.setEventTitle("维修通过");
            event.setCreatePerson(repair.getUserId());
            event.setCreateTime(DateUtils.getCurrentTime());
            event.setIsDel(0);
            result = eventDao.insertSelective(event);
            if(result == 0)
                throw new ExceptionUtil(500,MessageUtil.INSERTEVENTERROR,event);

            Thread t = new Thread(new Runnable() { //socket 推送
                @Override
                public void run() {
                    try {
                        sendUkeepMessageBySocket(repair);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            t.start();

            //创建群组
            new Thread(new EndChatGroupThread(repair.getRepairId()+"","1",webSocket_endRepairUrl)).start();

            new Thread(new HospitalConfirmSmsThread(repair.getRepairId(),1,userDao,repairDao,
                    null,repairByService2,null)).start();

            return new ReturnResultUtil(200,MessageUtil.SUCCESSFUL);
        }
    }

    /**
     * 查询维修详情
     * @param repairView
     * @return
     */
//    @Override
//    public ReturnResultUtil details(RepairView repairView){
//        Long repairId = repairView.getRepairId();
//        // 查询维修详情
//        RepairView details = repairDao.details(repairView);
//        // 查询时间轴信息
//        EventView eventView = new EventView();
//        eventView.setKeyId(repairId);
//        details.setEventList(eventDao.eventList(eventView));
//        //查询文件信息
//        FileView fileView = new FileView();
//        fileView.setKeyId(repairId);
//        fileView.setKeyType(1402L);
//        List<FileView> fileViews = fileDao.queryFiles(fileView);
//        details.setFileList(fileViews);
//        //查询配件信息
//        PartView partView = new PartView();
//        partView.setKeyId(repairId);
//        partView.setKeyType(1901L);
//        List<PartView> parts = partDao.queryPart(partView);
//        details.setPartList(parts);
//
//        //查询指派信息
//        Appoint appoint = new Appoint();
//        appoint.setKeyId(repairId);
//        appoint.setKeyType(2901L);
//        List<Appoint> appoints = appointDao.queryAppoints(appoint);
//        details.setAppointList(appoints);
//        return new ReturnResultUtil(200,MessageUtil.QUERYSUCCESS,details);
//    }

    @Override
    public ReturnResultUtil details(RepairView repairView) {
        RepairView detail = repairDao.queryRepairInfo(repairView);
        if(detail.getServiceType() != null){
            String serviceName= "";
            String serviceContacts = "";
            String servicePhone = "";
            if(detail.getServiceType().longValue() == 1105 || detail.getServiceType().longValue() == 1102){
                if(detail.getServiceType().longValue() == 1105 ){
                    serviceName = SupplierManufacturerInit.supplierManufacturerMap.get(detail.getServiceId()).getSupplierName();
                    serviceContacts = SupplierManufacturerInit.supplierManufacturerMap.get(detail.getServiceId()).getMasterContacts();
                    servicePhone = SupplierManufacturerInit.supplierManufacturerMap.get(detail.getServiceId()).getMasterPhone();
                }
                if(detail.getServiceType().longValue() == 1102 ){
                    serviceName = ManufacturerInit.manufacturerMaintainerMap.get(detail.getServiceId()).getManufacturerName();
                    serviceContacts = ManufacturerInit.manufacturerMaintainerMap.get(detail.getServiceId()).getMasterContacts();
                    servicePhone = ManufacturerInit.manufacturerMaintainerMap.get(detail.getServiceId()).getMasterPhone();
                }
                detail.setServiceName(serviceName);
                detail.setServiceContacts(serviceContacts);
                detail.setServicePhone(servicePhone);
            }
        }

        if(detail.getAppointList() != null && detail.getAppointList().size() > 0){
            int count = 0;
            for(AppointView av  : detail.getAppointList()){
                String instructName = "";
                count++;
                if(av.getInstructId() != null ){
                    av.setInstructTypeName(ItemInIt.itemMapByItemId.get(av.getInstructType()).getItem());
                    long instructId = av.getInstructId() == null ? 0L : av.getInstructId().longValue();
                    if(av.getInstructType().longValue() == 1102L){
                        instructName = ManufacturerInit.manufacturerMaintainerMap.get(instructId).getManufacturerName();
                    }else if(av.getInstructType().longValue() == 1105L){
                        instructName = SupplierManufacturerInit.supplierManufacturerMap.get(instructId).getSupplierName();
                    }else if(av.getInstructType().longValue() == 1103L){
                        instructName = MaintainerManufacturerInit.maintainerManufacturerMap.get(instructId).getMaintainerName();
                    }
                    av.setInstructName(instructName);
                }else{
                    av.setInstructName("平台");
                }
                if(av.getInstructedType() != null){
                    av.setInstructedTypeName(ItemInIt.itemMapByItemId.get(av.getInstructedType()).getItem());
                    long instructedId = av.getInstructedId() == null ? 0L : av.getInstructedId().longValue();
                    if(av.getInstructedType().longValue() == 1102L){
                        instructName = ManufacturerInit.manufacturerMaintainerMap.get(instructedId).getManufacturerName();
                    }else if(av.getInstructedType().longValue() == 1105L){
                        instructName = SupplierManufacturerInit.supplierManufacturerMap.get(instructedId).getSupplierName();
                    }else if(av.getInstructedType().longValue() == 1103L){
                        instructName = MaintainerManufacturerInit.maintainerManufacturerMap.get(instructedId).getMaintainerName();
                    }
                    av.setInstructedName(instructName);
                }

                if(count == detail.getAppointList().size()){
                    AppointView appoint =  av;
                    detail.setAppointView(appoint);
                }
            }
        }
        return new ReturnResultUtil(200,MessageUtil.QUERYSUCCESS,detail);
    }

    @Override
    @Transactional
    public ReturnResultUtil saveRepairData(RepairView repairView,User user) {
        DateFormat df  = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        repairView.setFrontStatus(2202L);
        int row = repairDao.updateByDistribution(repairView);
        if(row == 0)
            throw new ExceptionUtil(500,MessageUtil.INFOCOMPLETIONERROR);
        List<String> fileIds = repairView.getFileIds();
        if(fileIds != null && fileIds.size() > 0){
            for(String fileId : fileIds){
                File file = new File();
                file.setFileId(Long.parseLong(fileId));
                file.setKeyId(repairView.getRepairId());
                row = fileDao.updateByPrimaryKeySelective(file);
                if(row == 0)
                    throw new ExceptionUtil(500,MessageUtil.UPLOADEXCEPTION,file);
            }
        }
        if(repairView.getRepairDeviceEndStatus() != null){ //修改设备状态
            Device device = new Device();
            device.setDeviceId(repairView.getDeviceId());
            device.setDeviceStatus(repairView.getRepairDeviceEndStatus());
            row = deviceDao.updateByPrimaryKeySelective(device);
            if(row == 0)
                throw new ExceptionUtil(500,MessageUtil.UPDATEDEVICEERROR,device);
        }

        Event event1 = new Event();  //绑定事件
        event1.setEventTitle("确认维修");
        if(user.getTag().longValue() == 1005 || user.getTag().longValue() == 1006){
            Maintainer maintainer = maintainerDao.selectByPrimaryKey(user.getMaintainerId());
            event1.setEventContent(maintainer.getMaintainerName() + "的" + user.getRealName() + "已填写维修信息");
        }else{
            event1.setEventContent( "平台的" + user.getRealName() + "已填写维修信息");
        }
        event1.setEventId(UUIDGenerator.getUniqueLong());
        event1.setEventDateTime(df.format(new Date()));
        event1.setKeyType(1601L);
        event1.setKeyId(repairView.getRepairId());
        event1.setCreatePerson(repairView.getCreatePerson());
        event1.setCreateTime(df.format(new Date()));
        event1.setIsDel(0);
        row = eventDao.insertSelective(event1);
        if(row == 0)
            throw new ExceptionUtil(500,MessageUtil.INSERTEVENTERROR,event1);
        return new ReturnResultUtil(200,MessageUtil.SAVESUCCESS);
    }

//    @Override
//    public ReturnResultUtil queryRemind(ParameterView parameterView) {
//        Map<String,Object> map = new HashMap<String,Object>();
//        int row = repairDao.queryRemindCount(parameterView);
//        if(row > 0){
//            List<RepairView> repairViews = repairDao.queryRemind(parameterView);
//            map.put("data",repairViews);
//        }
//        map.put("count",row);
//        return new ReturnResultUtil(200,MessageUtil.QUERYSUCCESS,map);
//    }

    @Override
    public ReturnResultUtil queryRemind(Map map) {
        return new ReturnResultUtil(200,MessageUtil.QUERYSUCCESS,repairDao.queryRemind(map));
    }

    public void sendUkeepMessageBySocket(RepairView parameter){
        RepairView repairView = repairDao.details(parameter);
        SocketMessageView smv = new SocketMessageView();
        smv.setDeviceId(repairView.getDeviceId());
        smv.setRepairId(repairView.getRepairId());
        smv.setMessageType("body");
        smv.setKey(""+repairView.getRepairId() + repairView.getDeviceId());
        //无设备报修
        if(parameter.getType() != null && parameter.getType()==1){
            smv.setType(0);
            if(repairView.getStatus().longValue() == 2200){
                smv.setMessage(repairView.getHospitalName()+"申请了报修。");
            }else if(repairView.getStatus().longValue() == 2201){
                User user = userDao.selectByPrimaryKey(repairView.getTerraceHandlePerson());
                smv.setMessage("平台的"+user.getRealName()+"报修了设备并分配给服务商-"+ repairView.getMaintainerName());
            }else if(repairView.getStatus().longValue() == 2202){
                User user = userDao.selectByPrimaryKey(repairView.getEngineerId());
                smv.setMessage("服务商-"+ repairView.getMaintainerName()+"报修了设备并指派给负责人-"+ user.getRealName());
            }else if(repairView.getStatus().longValue() == 2203){
                User user = userDao.selectByPrimaryKey(repairView.getEngineerId());
                smv.setMessage("负责人-"+ user.getRealName()+"维修完毕");
            }else if(repairView.getStatus().longValue() == 2204){
                User user = userDao.selectByPrimaryKey(repairView.getHospitalConfirmPerson());
                smv.setMessage("负责人-"+ user.getRealName()+"确认设备维修已修复");
            }else if(repairView.getStatus().longValue() == 2205){
                User user = userDao.selectByPrimaryKey(repairView.getHospitalConfirmPerson());
                smv.setMessage("负责人-"+ user.getRealName()+"确认设备维修未修复");
            }
        }else{
            if(repairView.getStatus().longValue() == 2200){
                if(repairView.getDeviceStatus().longValue() == 1502){
                    smv.setType(1);
                }else if(repairView.getDeviceStatus().longValue() == 1501){
                    smv.setType(2);
                }
                smv.setMessage(repairView.getHospitalName()+"对设备-" +repairView.getDeviceName() + "。申请了报修。");
            }else if(repairView.getStatus().longValue() == 2201){
                User user = userDao.selectByPrimaryKey(repairView.getTerraceHandlePerson());
                smv.setMessage("平台的"+user.getRealName()+"将设备-" + repairView.getDeviceName()+"报修分配给服务商-"+ repairView.getMaintainerName());
            }else if(repairView.getStatus().longValue() == 2202){
                User user = userDao.selectByPrimaryKey(repairView.getEngineerId());
                smv.setMessage("服务商-"+ repairView.getMaintainerName()+"将设备-" + repairView.getDeviceName()+"报修指派给负责人-"+ user.getRealName());
            }else if(repairView.getStatus().longValue() == 2203){
                User user = userDao.selectByPrimaryKey(repairView.getEngineerId());
                smv.setMessage("负责人-"+ user.getRealName()+"将设备-" + repairView.getDeviceName()+"维修完毕");
            }else if(repairView.getStatus().longValue() == 2204){
                User user = userDao.selectByPrimaryKey(repairView.getHospitalConfirmPerson());
                smv.setMessage("负责人-"+ user.getRealName()+"确认设备-"+ repairView.getDeviceName()+"的维修已修复");
            }else if(repairView.getStatus().longValue() == 2205){
                User user = userDao.selectByPrimaryKey(repairView.getHospitalConfirmPerson());
                smv.setMessage("负责人-"+ user.getRealName()+"确认设备-"+ repairView.getDeviceName()+"的维修未修复");
            }
        }

        WSClientManager.sendMessage(JSON.toJSONString(smv));
    }

    @Override
    public ReturnResultUtil queryInfoPage(RepairView repairView,UserView sessionUser) {
        Repair repair = repairDao.selectByPrimaryKey(repairView.getRepairId());
        if(repair!=null){
            repairView.setServiceId(repair.getServiceId());
            repairView.setServiceType(repair.getServiceType());
            repairView.setServiceName(repair.getServiceName());
            repairView.setServiceContacts(repair.getServiceContacts());
            repairView.setServicePhone(repair.getServicePhone());
            repairView.setHospitalContacts(repair.getHospitalContacts());
            repairView.setHospitalPhone(repair.getHospitalPhone());
            repairView.setEngineerName(repair.getEngineerName());
            repairView.setEngineerPhone(repair.getEngineerPhone());
            repairView.setExamine(repair.getExamine());
            repairView.setExamineComment(repair.getExamineComment());
            repairView.setFaultTime(repair.getFaultTime());
            repairView.setFaultDepictHospital(repair.getFaultDepictHospital());
            repairView.setRepairPerson(repair.getRepairPerson());
            repairView.setRepairPersonPhone(repair.getRepairPersonPhone());
        }
        if(repairView.getDeviceId()==null){
            throw new ExceptionUtil(500,MessageUtil.DEVICEIDISNULL);
        }
        Device device = deviceDao.selectByPrimaryKey(repairView.getDeviceId());

        if(device.getContractDeviceId()==null){
            return new ReturnResultUtil(200, MessageUtil.QUERYSUCCESS,repairView);
        }
        ContractDevice contractDevice = contractDeviceDao.selectByPrimaryKey(device.getContractDeviceId());

        if(contractDevice.getContractId()==null){
            return new ReturnResultUtil(200, MessageUtil.QUERYSUCCESS,repairView);
        }
        Contract contract = contractDao.selectByPrimaryKey(contractDevice.getContractId());
        //厂商
        Manufacturer manufacturer = manufacturerDao.selectByPrimaryKey(contractDevice.getManufacturerId());
        //供应商
        Supplier supplier = supplierDao.selectByPrimaryKey(contract.getSecondParty());
        if(sessionUser.getMaintainerId()!=null){
            Maintainer maintainer = maintainerDao.selectByPrimaryKey(sessionUser.getMaintainerId());
            repairView.setMaintainer(maintainer);
        }
        //查询是保内还是保外
        if(repair==null){
            repairView.setServiceType(InsideOutsideUtil.queryWarranty(device.getEnableTime(),contractDevice.getDeviceWarrantyPeriod(),contractDevice.getSupplierWarrantyPeriod()));
        }
        repairView.setManufacturer(manufacturer);
        repairView.setSupplier(supplier);
        RepairView detail = repairDao.queryRepairInfo(repairView);
        if(detail!=null){
            repairView.setFileList(detail.getFileList());
        }
        return new ReturnResultUtil(200, MessageUtil.QUERYSUCCESS,repairView);
    }

    @Override
    public ReturnResultUtil disagree(RepairView repairView) {
        repairView.setExamine(0);//审核不通过
        //审核不通过将serviceType置空
        repairView.setServiceType(null);
        int result = repairDao.updateServiceType(repairView);
        if(result == 0)
            throw new ExceptionUtil(500,MessageUtil.UPDATEREPAIRERROR);

        Repair repair = repairDao.selectByPrimaryKey(repairView.getRepairId());
        DeviceView dc = deviceDao.queryDeviceInfo(repair.getDeviceId());
        Event event = new Event();
        // 添加报修事件
        event.setEventId(UUIDGenerator.getUniqueLong());
        event.setKeyType(1601L);
        event.setKeyId(repairView.getRepairId());       // 维修ID
        event.setEventDateTime(DateUtils.getCurrentTime());
        event.setEventContent(StringUtil.isEmpty(repair.getRepairPerson())==null?"":repair.getRepairPerson()+"于"+repair.getRepairTime()+
                "报修的("+dc.getDeviceName()+")平台审核不通过,待平台重新指派");
        event.setEventTitle("平台审核");
        event.setCreatePerson(repairView.getCreatePerson());
        event.setCreateTime(DateUtils.getCurrentTime());
        event.setIsDel(0);
        result = eventDao.insertSelective(event);
        if(result == 0)
            throw new ExceptionUtil(500,MessageUtil.FAILED,event);
        return new ReturnResultUtil(200, MessageUtil.SUCCESSFUL);
    }

    @Override
    public ReturnResultUtil agree(RepairView repairView) {
        repairView.setExamine(1);//审核通过
        if(repairView.getServiceType()==1103L){
            //新增一条维修商记录
            Maintainer maintainer = new Maintainer();
            maintainer.setMaintainerName(repairView.getServiceName());
            Maintainer maintainerView = maintainerDao.queryByMaintainerName(maintainer);
            if(maintainerView==null) {
                //新建维修商、
                maintainer.setMaintainerId(UUIDGenerator.getUniqueLong());
                maintainer.setMaintainerPhone(repairView.getServicePhone());
                maintainer.setMaintainerContacts(repairView.getServiceContacts());
                maintainer.setCreatePerson(repairView.getUserId());
                maintainer.setCreateTime(DateUtils.getCurrentTime());
                maintainer.setIsDel(1);
                int result = maintainerDao.insertSelective(maintainer);
                if(result == 0)
                    throw new ExceptionUtil(500,MessageUtil.FAILED,maintainer);
                //把维修商id存入维修表
                repairView.setServiceId(maintainer.getMaintainerId());

                Thread t = new Thread(new Runnable() {  //刷新缓存维修商
                    @Override
                    public void run() {
                        try {
                            MaintainerManufacturerInit maintainerManufacturerInit = new MaintainerManufacturerInit();
                            maintainerManufacturerInit.queryMaintainerManufacturer();

                            ManufacturerInit manufacturerInit = new ManufacturerInit();
                            manufacturerInit.queryManufacturerMaintainer();

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
                t.start();
            }else{
                repairView.setServiceId(maintainerView.getMaintainerId());
            }
        }
        //如果医院选择了指派工程师
//        if(repairView.getIsDispatch()==1){
//            String engineerPhone = repairView.getEngineerPhone();
//            String engineerName = repairView.getEngineerName();
//            ReturnResultUtil rru = userService.queryUserByEngineerPhone(engineerPhone,engineerName,repairView.getServiceId());
//            if(rru.getData() == null)
//                return new ReturnResultUtil(200, rru.getMsg());
//            User user = (User) rru.getData();
//            repairView.setEngineerId(user.getUserId());
//        }
        int result1 = repairDao.updateByPrimaryKeySelective(repairView);
        if(result1 == 0)
            throw new ExceptionUtil(500,MessageUtil.FAILED,repairView);

        Repair repair = repairDao.selectByPrimaryKey(repairView.getRepairId());
        DeviceView dc = deviceDao.queryDeviceInfo(repair.getDeviceId());
        // 添加事件
        Event event = new Event();
        event.setEventId(UUIDGenerator.getUniqueLong());
        event.setKeyType(1601L);
        event.setKeyId(repairView.getRepairId());       // 设备ID
        event.setEventDateTime(DateUtils.getCurrentTime());
        event.setEventContent(StringUtil.isEmpty(repair.getRepairPerson())==null?"":repair.getRepairPerson()+"于"+repair.getRepairTime()+
                "报修的("+dc.getDeviceName()+")平台审核通过");
        event.setEventTitle("平台审核");
        event.setCreatePerson(repairView.getUserId());
        event.setCreateTime(DateUtils.getCurrentTime());
        event.setIsDel(0);
        result1 = eventDao.insertSelective(event);
        if(result1 == 0)
            throw new ExceptionUtil(500,MessageUtil.INSERTEVENTERROR,event);
        return new ReturnResultUtil(200, MessageUtil.SUCCESSFUL);
    }

    private Appoint setAppoint(RepairView repairView,UserView sessionUser){
        Appoint appoint = new Appoint();
        appoint.setAppointId(UUIDGenerator.getUniqueLong());
        appoint.setKeyType(2901L);
        appoint.setKeyId(repairView.getRepairId());
        //指派方类型取登录用户type
        appoint.setInstructType(sessionUser.getType());
        appoint.setInstructedType(repairView.getServiceType());
        appoint.setCreateTime(DateUtils.getCurrentTime());
        appoint.setCreatePerson(sessionUser.getUserId());
        //登录用户的类型
        Long type = sessionUser.getType();
        if(type==1102L){
            appoint.setInstructId(sessionUser.getManufacturerId());
        }
        if(type==1105L){
            appoint.setInstructId(sessionUser.getSupplierId());
        }
        if(type==1103L){
            appoint.setInstructId(sessionUser.getMaintainerId());
        }
        //如果选择供应商
        if(repairView.getServiceType()==1105L){
            repairView.setExamine(1);
            appoint.setInstructedId(repairView.getServiceId());
        }
        //如果选择厂商
        if(repairView.getServiceType()==1102L){
            repairView.setExamine(1);
            appoint.setInstructedId(repairView.getServiceId());
        }
        //如果选择维修商
        if(repairView.getServiceType()==1103L){
            //判断维修商是否存在
            Maintainer maintainer = new Maintainer();
            maintainer.setMaintainerName(repairView.getServiceName());
            Maintainer maintainerView = maintainerDao.queryByMaintainerName(maintainer);
            if(maintainerView==null){
                //新建维修商、
                maintainer.setMaintainerId(UUIDGenerator.getUniqueLong());
                maintainer.setMaintainerPhone(repairView.getServicePhone());
                maintainer.setMaintainerContacts(repairView.getServiceContacts());
                maintainer.setCreatePerson(repairView.getUserId());
                maintainer.setCreateTime(DateUtils.getCurrentTime());
                maintainer.setIsDel(1);
                int result = maintainerDao.insertSelective(maintainer);
                if(result == 0)
                    return appoint;
                appoint.setInstructedId(maintainer.getMaintainerId());
                repairView.setServiceId(maintainer.getMaintainerId());

                Thread t = new Thread(new Runnable() {  //刷新缓存维修商
                    @Override
                    public void run() {
                        try {
                            MaintainerManufacturerInit maintainerManufacturerInit = new MaintainerManufacturerInit();
                            maintainerManufacturerInit.queryMaintainerManufacturer();

                            ManufacturerInit manufacturerInit = new ManufacturerInit();
                            manufacturerInit.queryManufacturerMaintainer();

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
                t.start();
            }else{
                if(repairView.getServiceId()==null){
                    appoint.setInstructedId(maintainerView.getMaintainerId());
                    repairView.setServiceId(maintainerView.getMaintainerId());
                }else{
                    appoint.setInstructedId(repairView.getServiceId());
                }
            }
        }
        if(repairView.getIsDispatch()==1){
            String engineerPhone = repairView.getEngineerPhone();
            repairView.setStatus(2206L);//工程师待确认状态***************************
            String engineerName = repairView.getEngineerName();
            ReturnResultUtil rru = userService.queryUserByEngineerPhone(engineerPhone,engineerName,repairView.getServiceId(),repairView.getServiceType());
            User user = (User) rru.getData();
            if(user==null)
                throw new ExceptionUtil(500,rru.getMsg());
            repairView.setEngineerId(user.getUserId());
            repairView.setEngineerName(engineerName);
            repairView.setEngineerPhone(engineerPhone);
            appoint.setEngineerName(engineerName);
            appoint.setEngineerPhone(engineerPhone);
        }
        return appoint;
    }


    @Override
    public ReturnResultUtil editEngineer(Appoint appoint, User user) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Appoint app = appointDao.selectByPrimaryKey(appoint.getAppointId());
        appoint.setInstructedId(app.getInstructedId());
        appoint.setInstructedType(app.getInstructedType());
        appoint.setAppointId(UUIDGenerator.getUniqueLong());
        appoint.setKeyId(app.getKeyId());
        appoint.setKeyType(app.getKeyType());
        appoint.setCreateTime(df.format(new Date()));
        appoint.setCreatePerson(user.getUserId());
        appoint.setAppointId(UUIDGenerator.getUniqueLong());
        ReturnResultUtil rru = userService.queryUserByEngineerPhone(appoint.getEngineerPhone(),appoint.getEngineerName(),appoint.getInstructedId(),appoint.getInstructedType());
        if(rru.getRet() == 500){
            return rru;
        }
        User u = (User) rru.getData();
        appoint.setEngineerId(u.getUserId());
        if(user.getType() == 1104L){
            appoint.setInstructId(null);
            appoint.setInstructType(u.getType());
        }else{
            appoint.setInstructId(app.getInstructedId());
            appoint.setInstructType(app.getInstructedType());
        }

        int result = appointDao.insertSelective(appoint);
        if(result > 0){
            Repair repair = repairDao.selectByPrimaryKey(app.getKeyId());
            //修改状态为待工程师处理
            repair.setStatus(2206L);
            repair.setEngineerId(appoint.getEngineerId());
            repair.setEngineerName(appoint.getEngineerName());
            repair.setEngineerPhone(appoint.getEngineerPhone());
            result = repairDao.updateByPrimaryKeySelective(repair);
            if(result == 0)
                throw new ExceptionUtil(500,MessageUtil.SAVEEXCEPTION,result);

            // 添加事件
            Event event = new Event();
            event.setEventId(UUIDGenerator.getUniqueLong());
            event.setKeyType(1601L);
            event.setKeyId(repair.getRepairId());       // 设备ID
            event.setEventDateTime(DateUtils.getCurrentTime());
            event.setEventContent(user.getRealName()+"修改了工程师为:"+appoint.getEngineerName()+",电话:"+appoint.getEngineerPhone());
            event.setEventTitle("工程师修改");
            event.setCreatePerson(user.getUserId());
            event.setCreateTime(DateUtils.getCurrentTime());
            event.setIsDel(0);
            result = eventDao.insertSelective(event);
            if(result == 0)
                throw new ExceptionUtil(500,MessageUtil.INSERTEVENTERROR,event);

            new Thread(new UpdateEngineerSmsThread(app.getKeyId(),1,repairDao,
                    null,repairByEngineer,null)).start();

            return new ReturnResultUtil(200,MessageUtil.SUCCESSFUL);
        }
        return new ReturnResultUtil(200,MessageUtil.FAILED);
    }

    public ReturnResultUtil reject(RepairView repairView) {
        Repair repair = repairDao.selectByPrimaryKey(repairView.getRepairId());
        //复制一条数据
        Repair rv = new Repair();
        BeanUtils.copyProperties(repair,rv);
        rv.setRepairId(UUIDGenerator.getUniqueLong()); // ID
        rv.setIsDel(1);
        int result = repairDao.insertSelective(rv);
        if(result > 0){
            //将源数据相关字段置空，并将状态更改为待处理：2200
            repair.setRepairTime(null);
//            repair.setRepairPerson(null);
//            repair.setRepairPersonPhone(null);
//            repair.setFaultTime(null);
//            repair.setUrgentDegree(null);
//            repair.setFaultTime(null);
//            repair.setDeviceStatus(null);
            repair.setStatus(2200L);
            repair.setHandleTime(null);
            repair.setServiceId(null);
            repair.setServiceType(null);
            repair.setServiceName(null);
            repair.setServiceContacts(null);
            repair.setServicePhone(null);
            repair.setDispatchTime(null);
            repair.setEngineerId(null);
            repair.setRepairDeviceStartStatus(null);
            repair.setRepairDeviceEndStatus(null);
            repair.setRepairMode(null);
            repair.setRepairContent(null);
            repair.setFaultDepictEngineer(null);
            repair.setTravelTime(null);
            repair.setRepairEndTime(null);
            repair.setComment(null);
            repair.setRemark(null);
            repair.setTerraceHandlePerson(null);
            repair.setCommentStatus(3502L);
            repair.setEngineerExpectedTime(null);
            repair.setEngineerResponseTime(null);
            repair.setEngineerName(null);
            repair.setEngineerPhone(null);
            repair.setExamine(null);
            repair.setExamineComment(null);
            result = repairDao.updateRepairSetNull(repair);
            if(result == 0)
                throw new ExceptionUtil(500,MessageUtil.FAILED,repair);

            // 添加事件
            Event event = new Event();
            event.setEventId(UUIDGenerator.getUniqueLong());
            event.setKeyType(1601L);
            event.setKeyId(repairView.getRepairId());       // 设备ID
            event.setEventDateTime(DateUtils.getCurrentTime());
            event.setEventContent("医院审核不通过，待平台联系医院");
            event.setEventTitle("维修不通过");
            event.setCreatePerson(repairView.getUserId());
            event.setCreateTime(DateUtils.getCurrentTime());
            event.setIsDel(0);
            result = eventDao.insertSelective(event);
            if(result == 0)
                throw new ExceptionUtil(500,MessageUtil.INSERTEVENTERROR,event);

            Thread t = new Thread(new Runnable() { //socket 推送
                @Override
                public void run() {
                    try {
                        sendUkeepMessageBySocket(repairView);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            t.start();
            new Thread(new EndChatGroupThread(repairView.getRepairId()+"","1",webSocket_endRepairUrl)).start();

            new Thread(new HospitalNotConfirmSmsThread(repairView.getRepairId(),1,userDao,repairDao,
                    null,repairByPlatform2,null)).start();

            return new ReturnResultUtil(200,MessageUtil.SUCCESSFUL);
        }
        return new ReturnResultUtil(200,MessageUtil.FAILED);
    }

    @Override
    public ReturnResultUtil queryDeviceIsRepair(Long deviceId) {
        int result = repairDao.queryDeviceIsRepair(deviceId);
        if(result>0){
            return new ReturnResultUtil(200,MessageUtil.DEVICEISREPAIR,1);
        }
        return new ReturnResultUtil(200,MessageUtil.QUERYSUCCESS);
    }

    private String getName(Long serviceType) {
        String name="";
        if(serviceType==1102L) {
            return "厂商";
        }else if(serviceType==1103L){
            return "维修商";
        }else if(serviceType==1105L){
            return "经销商";
        }
        return name;
    }

    /**
     * 添加报修
     * @param repair
     * @return
     */
    @Override
    @Transactional
    public ReturnResultUtil addRepair(RepairView repair){
        // 添加报修
        repair.setRepairId(UUIDGenerator.getUniqueLong()); // ID
        repair.setRepairNo("WX"+UUIDGenerator.getUniqueLong());// 报修编号
        repair.setRepairTime(DateUtils.getCurrentTime());  //报修时间
        repair.setRepairDeviceStartStatus(repair.getDeviceStatus());
        repair.setStatus(2200L);                           // 待处理
        repair.setCommentStatus(3502L);                    //未评论(已评论:3501,未评论:3502,已回复:3503)
        repair.setIsDel(0);                                // 禁用状态（1禁用，0正常）
        repair.setCreatePerson(repair.getUserId());          // 创建人
        repair.setCreateTime(DateUtils.getCurrentTime());  // 创建时间

        if(repair.getValidateCode()!=null){
            //校验验证码
            ValidateCode validateCode = new ValidateCode();
            validateCode.setMobile(repair.getRepairPersonPhone());
            validateCode.setCode(repair.getValidateCode());
            ValidateCode vc = validateCodeDao.verificationCode(validateCode);
            if(vc==null){
                throw new ExceptionUtil(500,MessageUtil.MOBILEORCODEERROR);
            }
        }


        int result = repairDao.insertSelective(repair);
        // 添加成功
        if(result > 0){
            //修改医院地址
            Hospital hospital = hospitalDao.selectByPrimaryKey(repair.getHospitalId());
            hospital.setAddress(repair.getAddress());
            hospitalDao.updateByPrimaryKeySelective(hospital);

            List<String> fileIds = repair.getFileIds();
            if(fileIds != null && fileIds.size()>0){
                for(String fileId : fileIds){
                    File file = new File();
                    file.setFileId(Long.parseLong(fileId));
                    file.setKeyId(repair.getRepairId());
                    result = fileDao.updateByPrimaryKeySelective(file);
                    if(result == 0)
                        throw new ExceptionUtil(500,MessageUtil.UPLOADEXCEPTION,file);
                }
            }

            // 创建事件对象
            Event event = new Event();
            // 添加报修事件
            event.setEventId(UUIDGenerator.getUniqueLong());
            event.setKeyType(1601L);
            event.setKeyId(repair.getRepairId());       // 维修ID
            event.setEventDateTime(DateUtils.getCurrentTime());
            //什么都没选择
            if(repair.getServiceType()==null){
                event.setEventContent(StringUtil.isEmpty(repair.getRepairPerson())==null?"":repair.getRepairPerson()+"于"+repair.getRepairTime()+"报修了设备,待平台处理");
            }else{
                if(repair.getIsDispatch()==1){
                    event.setEventContent(StringUtil.isEmpty(repair.getRepairPerson())==null?"":repair.getRepairPerson()+"于"+repair.getRepairTime()+
                            "报修了设备,并安排"+getName(repair.getServiceType())+"("+ repair.getServiceName()+")指派了工程师("+repair.getEngineerName()+")维修,待平台处理");
                }else{
                    event.setEventContent(StringUtil.isEmpty(repair.getRepairPerson())==null?"":repair.getRepairPerson()+"于"+repair.getRepairTime()+
                            "报修了设备,并安排"+getName(repair.getServiceType())+"("+ repair.getServiceName()+"),待平台处理");
                }
            }
            event.setEventTitle("申请报修");
            event.setCreatePerson(repair.getCreatePerson());
            event.setCreateTime(DateUtils.getCurrentTime());
            event.setIsDel(0);
            result = eventDao.insertSelective(event);
            if(result == 0)
                throw new ExceptionUtil(500,MessageUtil.INSERTEVENTERROR);
            // 添加设备事件
            event.setEventId(UUIDGenerator.getUniqueLong());
            event.setKeyType(1601L);
            event.setKeyId(repair.getDeviceId());       // 设备ID
            event.setEventDateTime(DateUtils.getCurrentTime());
            if(repair.getIsDispatch()==1){
                event.setEventContent("医院-"+repair.getHospitalName()+"向"+repair.getServiceName()+"申请报修,处理人为："+repair.getEngineerName());
            }else{
                event.setEventContent("设备申请报修");
            }
            event.setEventTitle("设备报修");
            event.setType(1700L);
            event.setCreatePerson(repair.getCreatePerson());
            event.setCreateTime(DateUtils.getCurrentTime());
            event.setIsDel(0);
            result = eventDao.insertSelective(event);
            if(result == 0)
                throw new ExceptionUtil(500,MessageUtil.INSERTEVENTERROR);

            repair.setType(1);
            Thread t = new Thread(new Runnable() { //socket 推送
                @Override
                public void run() {
                    try {
                        sendUkeepMessageBySocket(repair);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            t.start();

            //创建群组
            new Thread(new ChatGroupThread(repair.getRepairId()+"",webSocket_InsertRepairUrl)).start();

//            //推送短信给平台管理员
//            String hospitalName = dc.getHospitalName();
//            String deviceName = dc.getDeviceName();
//            String sn = dc.getSn();
//
//            new Thread(new RepairSendSmsThread(hospitalName,deviceName,sn,userDao,repairByPlatform1,null)).start();

            //判断登陆手机号是否在库中存在，否则新建用户
            UserView uv = userDao.loginUser(repair.getRepairPersonPhone());
            if(uv == null){
                uv = new UserView();
                uv.setUserName(repair.getRepairPersonPhone());
                uv.setMobile(repair.getRepairPersonPhone());
                uv.setRealName("新用户");
                uv.setHospitalId(repair.getHospitalId());
                uv.setType(1101L);
                uv.setTag(1002L);
                uv.setIsDel(0);
                uv.setUserId(UUIDGenerator.getUniqueLong());
                uv.setLoginType(2);
                uv.setOpenId(repair.getOpenId());
                userDao.insertSelective(uv);

                UserView users = userDao.loginUser(uv.getUserName());
                if(users != null){
                    UserView loginUser = loginUser(users);
                    CacheData.addSessionUser((UserView) loginUser,1);
                    if(StringUtil.isEmpty(users.getPassword())){
                        loginUser.setStatus(100);
                    }
                    return new ReturnResultUtil(200,MessageUtil.LOGINSUCCESS,loginUser);
                }
            }
            return new ReturnResultUtil(200, MessageUtil.SAVESUCCESS,repair);
        }
        return new ReturnResultUtil(200, MessageUtil.SAVEEXCEPTION);
    }

    public UserView loginUser(UserView userView){
        if(userView == null){
            return null;
        }
        String secretKey = UUIDGenerator.generate(userView.getUserId());
        UserView userView1 = new UserView();
        userView1.setUserId(userView.getUserId());
        userView1.setHospitalName(userView.getHospitalName());
        userView1.setMaintainerName(userView.getMaintainerName());
        userView1.setManufacturerName(userView.getManufacturerName());
        userView1.setHospitalId(userView.getHospitalId());
        userView1.setManufacturerId(userView.getManufacturerId());
        userView1.setMaintainerId(userView.getMaintainerId());
        userView1.setMobile(userView.getMobile());
        userView1.setStatus(userView.getStatus());
        userView1.setTag(userView.getTag());
        userView1.setRealName(userView.getRealName());
        userView1.setType(userView.getType());
        userView1.setUserName(userView.getUserName());
        userView1.setSecretKey(secretKey);
        userView1.setSupplierId(userView.getSupplierId());
        userView1.setSupplierName(userView.getSupplierName());
        userView1.setCommissionId(userView.getCommissionId());
        userView1.setCommissionName(userView.getCommissionName());
        return userView1;
    }
}
